package com.itboye.jigongbao.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.View
import android.widget.*
import com.itboye.jigongbao.R
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseActivity
import com.itboye.jigongbao.bean.LoginInfo
import com.itboye.jigongbao.bean.UpdateImageBean
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.ImageCompress
import com.itboye.jigongbao.utils.SPUtils.clear
import com.itboye.jigongbao.utils.SPUtils.getSp
import com.itboye.jigongbao.utils.TitleBarUtils
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import com.itboye.jigongbao.utils.XGlideLoader
import com.itboye.jigongbao.utils.permission.PermissionListener
import com.umeng.message.UTrack
import com.yancy.gallerypick.config.GalleryPick
import com.yancy.gallerypick.inter.IHandlerCallBack
import kotlinx.android.synthetic.main.activity_mine.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class MineActivity : BaseActivity(), Observer {
    private fun setCacheData() {
        var loginInfo = MyApplication.instance!!.mACache!!.getAsObject(Const.LOGIN_INFO) as LoginInfo
        loginInfo!!.setNickname(nickname)
        loginInfo!!.setRealname(realname)
        loginInfo!!.setSex(sex)
        loginInfo!!.setNation(nation)
        loginInfo!!.setBirthday(mBirth)
        loginInfo!!.setHometown(hometown)
        loginInfo!!.setWorks_cate(works_cate)
        loginInfo!!.setProfession(profession)
        loginInfo!!.setWorking_years(working_years)
        this.loginInfo = loginInfo
        //重新put进去
        MyApplication.instance!!.mACache!!.put(Const.LOGIN_INFO, loginInfo)
    }


    override fun update(p0: Observable?, p1: Any?) {
        var entity = p1 as ResultEntity
        when (entity.eventType) {
            UserPrestener.By_UserProfile_update_Success -> {
                ByAlert.alert(entity.msg)
                setCacheData()//更新用户本地缓存数据
                //更新Application中的LoginInfo数据
                MyApplication.instance!!.loginInfo = loginInfo
                finish()
            }
            UserPrestener.By_UserProfile_update_Fail -> {
                ByAlert.alert(entity.msg)

            }
            UserPrestener.avatar_Success -> {
                var update = entity.data as UpdateImageBean.UploadImageDataBean
                ByAlert.alert(entity.msg)
                if (MyApplication.instance!!.mACache!!.getAsObject(Const.LOGIN_INFO) != null) {
                    setUserData()//更新头像
                }
            }
            UserPrestener.avatar_Fail -> {
                ByAlert.alert(entity.msg)
            }
            else -> {
            }
        }

    }

    companion object {
        var minActivity: MineActivity? = null
        var tv_hometown_value: TextView? = null
        fun setAddress(address: String) {
            tv_hometown_value!!.setText(address)
        }
    }


    var tv_actionbar_right: TextView? = null
    var iv_actionbar_left: ImageView? = null
    var btn_exit_login: Button? = null
    var re_head: RelativeLayout? = null
    var re_birth: RelativeLayout? = null
    var re_sex: RelativeLayout? = null
    var loginInfo: LoginInfo? = null

    var userPresenter: UserPrestener? = null

    var REQUEST_CAMERA_CODE: Int = 101

    var simpleDataFormat: SimpleDateFormat? = null

    private var iHandlerCallBack: IHandlerCallBack? = null
    var re_hometown: RelativeLayout? = null


    private val path = ArrayList<String>()
    override fun getLayoutId(): Int {
        return R.layout.activity_mine
    }

    override fun initData() {
        TitleBarUtils().initTitlebarStyle1(this, this!!.trans_action_bar_mine!!, "我的消息", R.drawable.img_back, "", 0, "保存")
        minActivity = this
        simpleDataFormat = SimpleDateFormat("yyyy-MM-dd")
        userPresenter = UserPrestener(this)
        initGallery()

        loginInfo = MyApplication.instance!!.loginInfo
    }

    private fun initGallery() {
        iHandlerCallBack = object : IHandlerCallBack {
            override fun onStart() {
                Log.i(Const.TAG_DEBUG, "onStart: 开启")
            }

            override fun onSuccess(photoList: List<String>) {
                path.clear()
                for (s in photoList) {
                    Log.i(Const.TAG_DEBUG, s)
                    path.add(s)
                }
                if (path.size > 0) {
                    var imagePath = path[0]
                    var file = File(ImageCompress.compress(imagePath))//File(imagePath)
                    //压缩图片
                    try {
                            userPresenter!!.avatar("avatar", MyApplication.instance!!.loginInfo!!.getUid().toString(), "", "", file.name, file, this@MineActivity)
                    }catch (e:Exception){
                        ByAlert.alert(e.toString())
                    }
                }
                Log.i(Const.TAG_DEBUG, "onSuccess: 返回数据--" + path.toString())
            }

            override fun onCancel() {
                Log.i(Const.TAG_DEBUG, "onCancel: 取消")
            }

            override fun onFinish() {
                Log.i(Const.TAG_DEBUG, "onFinish: 结束")
            }

            override fun onError() {
                Log.i(Const.TAG_DEBUG, "onError: 出错")
            }
        }
        MyApplication.instance!!.galleryConfig!!.builder.iHandlerCallBack(iHandlerCallBack).pathList(path).maxSize(1).build()
    }

    override fun onResume() {
        super.onResume()
        if (MyApplication.instance!!.mACache!!.getAsObject(Const.LOGIN_INFO) != null) {
            setUserData()
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onSaveInstanceState(outState: Bundle?) {
//        super.onSaveInstanceState(outState)
    }

    private fun setUserData() {
        XGlideLoader.displayImageCircularForUser(this, Const.Companion.avatar + loginInfo!!.getUid(), iv_head)
        setTextOrEditTextValue(et_nickname_value, loginInfo!!.getNickname())
        setTextOrEditTextValue(et_name_value, loginInfo!!.getRealName())
        setTextOrEditTextValue(tv_sex_value, loginInfo!!.getSex().toString())
        setTextOrEditTextValue(tv_minzu_value, loginInfo!!.getNation().toString())
        setTextOrEditTextValue(tv_birth_value, loginInfo!!.getBirthday())

        nickname = loginInfo!!.getNickname()
        realname = loginInfo!!.getRealName()
        sex = loginInfo!!.getSex()
        nation = loginInfo!!.getNation()
        birth = loginInfo!!.getBirthday()!! / 1000
        hometown = loginInfo!!.getHometown()
        works_cate = loginInfo!!.getWorks_cate()//工程类型
        profession = loginInfo!!.getProfession()//工种
        working_years = loginInfo!!.getWorking_years()//工龄
        setTextOrEditTextValue(tv_hometown_value, hometown)
        setTextOrEditTextValue(tv_gongcheng_type_value, works_cate)
        setTextOrEditTextValue(tv_gongzhong_value, profession)
        setTextOrEditTextValue(tv_gongling_value, working_years)

    }

    private fun setTextOrEditTextValue(view: Any?, value: Any?) {
        when (view) {
            is TextView -> {
                when (view.id) {
                    R.id.tv_sex_value -> {
                        if (value.toString().equals("0")) {
                            tv_sex_value.text = "女"
                        } else if (value.toString().equals("1")) {
                            tv_sex_value.text = "男"
                        }
                    }
                    R.id.tv_birth_value -> {
                        if (value != null) {
                            tv_birth_value.text = simpleDataFormat!!.format(value.toString().toLong() * 1000)
                        }
                    }
                    else -> {
                        view.text = value.toString()
                    }
                }
            }
            is EditText -> {
                view.setText(value.toString())
            }
            else -> {
            }
        }

    }

    var nickname: String? = null
    var realname: String? = null
    var sex: Int = 0//性别
    var working_years: Int = 0//工龄
    var nation: String? = null
    var mBirth: Int? = 0
    var hometown: String? = null
    var works_cate: String? = null
    var profession: String? = null
    override fun onClick(p0: View?) {
        when (p0) {
            tv_actionbar_right -> {
                nickname = et_nickname_value.text.toString()
                realname = et_name_value.text.toString()
                sex = if (tv_sex_value.text.toString().equals("男")) {
                    1
                } else if (tv_sex_value.text.toString().equals("女")) {
                    0
                } else {
                    2
                }
                nation = tv_minzu_value.text.toString()
                mBirth = birth
                hometown = tv_hometown_value.text.toString()
                works_cate = tv_gongcheng_type_value.text.toString()//工程类型
                profession = tv_gongzhong_value.text.toString()//工种
                working_years = tv_gongling_value.text.toString().toInt()//工龄
                //先上传头像
                userPresenter!!.By_UserProfile_update(MyApplication.instance!!.loginInfo!!.getUid().toString(), nickname, "", sex, realname, "", 2, mBirth.toString(), hometown, nation, profession, works_cate, working_years, 1, this)
            }
            iv_actionbar_left -> {
                finish()
            }
            btn_exit_login -> {
                Log.v(Const.TAG_DEBUG, "" + getSp(Const.ROLE))
                clear(this, null)
                MyApplication.instance!!.mACache!!.clear()
                Log.v(Const.TAG_DEBUG, "" + getSp(Const.ROLE))
                //移除友盟alias
                MyApplication.instance!!.mPushAgent!!.removeAlias(MyApplication.instance!!.loginInfo!!.getUid().toString(), Const.UMNG_ALIAS, object : UTrack.ICallBack {
                    override fun onMessage(p0: Boolean, p1: String?) {
                        Log.v(Const.TAG_DEBUG, "removeAlias onMessage result = $p0 and p1= $p1")
                    }

                })
                //关闭所有Activity
                MyApplication.instance!!.removeAllActivity()
                //重新进入登录页面
                startActivity(Intent(this, LoginActivity::class.java))
//                SPUtils.put(this,null, Const.ROLE,"")
//                SPUtils.put(this,null, Const.ROLE,"")
//                SPUtils.put(this,null, Const.ROLE,"")
            }
            re_head -> {//选择头像
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestRunPermission()
                } else {
                    gotoSelectPhoto()
                }
            }
            re_birth -> {
                showDatePickDlg()
            }
            re_sex -> {
                showSexDlg()
            }
            re_hometown -> {
                var intent = Intent(MineActivity@ this, ProvinceActivity::class.java)
                intent.putExtra("type", "province")
                startActivityForResult(intent, 101)
            }
            else -> {
            }
        }
    }

    var ad: AlertDialog? = null
    fun showSexDlg() {
        val sexs = arrayOf("男", "女")
        var index = 0
        var defaultIndex = if (MyApplication.instance!!.loginInfo!!.getSex() == 0) {
            1
        } else {
            0
        }
        ad = AlertDialog.Builder(this@MineActivity)
                .setTitle("选择性别")
                .setSingleChoiceItems(sexs, defaultIndex, object : DialogInterface.OnClickListener {
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        index = p1
                    }

                })
                .setPositiveButton("确定", object : DialogInterface.OnClickListener {
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        tv_sex_value.text = sexs[index]
                        ad!!.dismiss()
                    }

                })
                .setNegativeButton("取消", object : DialogInterface.OnClickListener {
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        ad!!.dismiss()
                    }

                })
                .create()

        ad!!.show()
    }

    private var birth: Int? = null

    protected fun showDatePickDlg() {
        val calendar = Calendar.getInstance()
        val datePickerDialog = DatePickerDialog(this@MineActivity, object : DatePickerDialog.OnDateSetListener {
            override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
                this@MineActivity.tv_birth_value.setText(year.toString() + "-" + (monthOfYear + 1) + "-" + dayOfMonth)
                var date = simpleDataFormat!!.parse(tv_birth_value.text.toString())
                birth = (date.time / 1000).toInt()
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
        datePickerDialog.show()

    }

    private fun requestRunPermission() {
        // 缺少权限时, 进入权限配置页面

        requestRunPermisssion(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), object : PermissionListener {
            override fun onGranted() {
                gotoSelectPhoto()
            }

            override fun onDenied(deniedPermission: List<String>) {
//                    for (permission in deniedPermission) {
//                        ByAlert.alert("被拒绝的权限：" + permission)
//                    }
//                    ByAlert.alert("被拒绝的权限：" + deniedPermission.toString())
                if (deniedPermission!!.size > 0) {
                    showPermission(this@MineActivity)
                }
            }
        })
    }

    private fun gotoSelectPhoto() {
        GalleryPick.getInstance().setGalleryConfig(MyApplication.instance!!.galleryConfig).open(this@MineActivity)
    }
}
